package com.kyivmohyla.kma2.client.presenter.refbook;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.kyivmohyla.kma2.client.UserService;
import com.kyivmohyla.kma2.client.events.manager.ManagerLoginEvent;
import com.kyivmohyla.kma2.client.gin.Injector;
import com.kyivmohyla.kma2.client.presenter.Presenter;
import com.kyivmohyla.kma2.client.utils.Dialog;
import com.kyivmohyla.kma2.shared.model.UIEquipment;
import com.kyivmohyla.kma2.shared.model.UIRefs;
import com.kyivmohyla.kma2.shared.model.UIService;
import com.kyivmohyla.kma2.shared.model.UIStaff;
import com.smartgwt.client.types.AnimationAcceleration;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.TreeModelType;
import com.smartgwt.client.widgets.events.DrawEvent;
import com.smartgwt.client.widgets.events.DrawHandler;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.RecordDoubleClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordDoubleClickHandler;
import com.smartgwt.client.widgets.tree.Tree;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.smartgwt.client.widgets.tree.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class TreeGridViewPresenter implements Presenter {

    private final Display display;
    private final Injector injector = Injector.INSTANCE;
    private String type;
    private List<UIEquipment> equipmentOnService;
    private UIStaff currentStaff;

    public TreeGridViewPresenter(String type, UIStaff currentStaff) {
        final DialogBox waiter = Dialog.getInstance().createWaiter();
        this.currentStaff = currentStaff;
        this.display = injector.getTreeGridView();
        equipmentOnService = new ArrayList<UIEquipment>();
        this.type = type;
        if (type.equals("Service")) {
            display.getRefsInfo().setVisible(true);
            UserService.App.getInstance().getServiceAllService(new AsyncCallback<List<UIService>>() {
                @Override
                public void onFailure(Throwable throwable) {
                    waiter.hide();
                    Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                }

                @Override
                public void onSuccess(List<UIService> result) {
                    waiter.hide();
                    redrawService(result);
                }
            });
        } else if (type.equals("Equipment")) {
            display.getRefsInfo().setVisible(false);
            UserService.App.getInstance().getEquipmentAllEquipment(new AsyncCallback<List<UIEquipment>>() {
                @Override
                public void onFailure(Throwable throwable) {
                    waiter.hide();
                    Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                }

                @Override
                public void onSuccess(List<UIEquipment> result) {
                    waiter.hide();
                    redrawEquipment(result);
                }
            });
        }
        bind();
    }

    private void bind() {
        this.display.getAddNodeButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doAddNode();
            }
        });
        this.display.getDeleteNodeButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doDeleteNode();
            }
        });
        this.display.getEditButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doEditNode();
            }
        });
        this.display.getBackButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                doGoBack();
            }
        });
    }

    private void createEquipmentDialogBox(final UIService selectedService) {
        final DialogBox waiter = Dialog.getInstance().createWaiter();
        final DialogBox dialogBox = new DialogBox();
        dialogBox.getElement().getStyle().setZIndex(500000);
        dialogBox.addStyleName("gwt-DialogBox");
        dialogBox.setText("Manage Equipment for Service \"" + selectedService.getName() + ", id = " + selectedService.getServiceId() + "\"");
        final VerticalPanel dialogContents = new VerticalPanel();
        dialogContents.addStyleName("dialogContents");
        dialogBox.setWidget(dialogContents);
        dialogContents.setSpacing(4);

        List<UIService> serviceList = new ArrayList<UIService>();
        serviceList.add(selectedService);

        UserService.App.getInstance().getEquipmentByServicesList(serviceList, new AsyncCallback<List<UIEquipment>>() {
            @Override
            public void onFailure(Throwable caught) {
                waiter.hide();
                Dialog.getInstance().createDialogBoxWithMessage("Message", "Something went wrong, maybe no connection to the Database. </br> Anyway, here's the original message " + caught.getMessage());
            }

            @Override
            public void onSuccess(List<UIEquipment> result) {
                //now we have all equipment used for this service from REFS table
                //let us create equipment treeGrid and check these equipment
                equipmentOnService.clear();
                equipmentOnService.addAll(result);

                final EquipmentReferenceBookPresenter eRBP = new EquipmentReferenceBookPresenter(result, null);
                waiter.hide();
                ((Button) eRBP.getDisplay().getAddButton()).setVisible(false);
                ((Button) eRBP.getDisplay().getSaveChangesButton()).setVisible(true);
                dialogContents.add(eRBP.getDisplay().asWidget());
                dialogBox.setGlassEnabled(true);
                dialogBox.setAnimationEnabled(true);
                dialogBox.center();
                dialogBox.show();
                //DONE now all equipment are ready

                eRBP.getDisplay().getCancelButton().addClickHandler(new ClickHandler() {
                    @Override
                    public void onClick(ClickEvent event) {
                        dialogBox.hide();
                    }
                });
                eRBP.getDisplay().getSaveChangesButton().addClickHandler(new ClickHandler() {
                    @Override
                    public void onClick(ClickEvent event) {
                        //here we have to save all stuff to REFS table
                        final DialogBox saveWaiter = Dialog.getInstance().createWaiter();
                        final List<UIEquipment> newEquipmentOnService = new ArrayList<UIEquipment>();
                        ListGridRecord[] records = eRBP.getDisplay().getTreeGrid().getSelectedRecords();
                        for (ListGridRecord record : records) {
                            if (record.getAttribute("ReportsTo") != null) {
                                UIEquipment equipment = new UIEquipment(record.getAttributeAsInt("Id"), record.getAttribute("Name"), 0, record.getAttributeAsInt("ReportsTo"), record.getAttribute("Description"));
                                newEquipmentOnService.add(equipment);
                            }
                        }
                        //now we have a list of all selected equipment
                        //let us put necessary entries to the database
                        //without any duplications
                        final List<UIEquipment> equipmentToDelete = new ArrayList<UIEquipment>();
                        final List<UIEquipment> equipmentToInsert = new ArrayList<UIEquipment>();
                        final List<UIRefs> refsToInsert = new ArrayList<UIRefs>();
                        final List<UIRefs> refsToDelete = new ArrayList<UIRefs>();
                        for (UIEquipment obj : newEquipmentOnService)
                            if (!equipmentOnService.contains(obj)) {
                                refsToInsert.add(new UIRefs(selectedService.getServiceId(), obj.getEquipmentId()));
                                equipmentToInsert.add(obj);
                            }
                        for (UIEquipment obj : equipmentOnService)
                            if (!newEquipmentOnService.contains(obj)) {
                                refsToDelete.add(new UIRefs(selectedService.getServiceId(), obj.getEquipmentId()));
                                equipmentToDelete.add(obj);
                            }
                        //we have chosen which entries we have to delete, and which - to insert
                        //let us first delete
                        UserService.App.getInstance().deleteRefsList(refsToDelete, new AsyncCallback<Void>() {
                            @Override
                            public void onFailure(Throwable caught) {
                                saveWaiter.hide();
                                Dialog.getInstance().createDialogBoxWithMessage("Message", "Something went wrong, maybe no connection to the Database. </br> Anyway, here's the original message " + caught.getMessage());
                            }

                            @Override
                            public void onSuccess(Void result) {
                                //and now insert
                                UserService.App.getInstance().addRefsList(refsToInsert, new AsyncCallback<Void>() {
                                    @Override
                                    public void onFailure(Throwable caught) {
                                        saveWaiter.hide();
                                        Dialog.getInstance().createDialogBoxWithMessage("Message", "Something went wrong, maybe no connection to the Database. </br> Anyway, here's the original message " + caught.getMessage());
                                    }

                                    @Override
                                    public void onSuccess(Void result) {
                                        // now we have to update equipmentOnService variable
                                        saveWaiter.hide();
                                        equipmentOnService.addAll(equipmentToInsert);
                                        equipmentOnService.removeAll(equipmentToDelete);
                                        Dialog.getInstance().createDialogBoxWithMessage("Success", "Changes were saved. Now please, dismiss this message.");
                                    }
                                });
                            }
                        });

                    }
                });

            }
        });
    }

    private void redrawService(List<UIService> result) {
        final DialogBox waiter = Dialog.getInstance().createWaiter();
        TreeGridField ServiceIdField = new TreeGridField("Id");
        TreeGridField NameField = new TreeGridField("Name");
        TreeGridField DescriptionField = new TreeGridField("Description");
        display.getTreeGrid().setFields(ServiceIdField, NameField, DescriptionField);
        display.getTreeGrid().addRecordDoubleClickHandler(new RecordDoubleClickHandler() {
            @Override
            public void onRecordDoubleClick(RecordDoubleClickEvent event) {
                if (event.getRecord().getAttribute("isFolder") == null) {
                    event.cancel();
                    try {
                        createEquipmentDialogBox(new UIService(event.getRecord().getAttributeAsInt("Id"), event.getRecord().getAttribute("Name"), 0, event.getRecord().getAttributeAsInt("ReportsTo"), event.getRecord().getAttribute("Description")));
                    } catch (NullPointerException e) {
                        Dialog.getInstance().createDialogBoxWithMessage("Message", "You can not add equipment to category entry");
                    }
                } else {
                    display.getTreeGrid().toggleFolder((TreeNode) event.getRecord());
                }
            }
        });

        final Tree tree = new Tree();
        tree.setModelType(TreeModelType.PARENT);
        tree.setNameProperty("Name");
        tree.setIdField("Id");
        tree.setParentIdField("ReportsTo");
        tree.setShowRoot(false);
        TreeNode[] treeNodes = new TreeNode[result.size()];
        for (int i = 0; i < treeNodes.length; ++i) {
            int parentId;
            if (result.get(i).getIsParent() == 1) {
                parentId = 0;
            } else {
                parentId = result.get(i).getParentId();
            }
            treeNodes[i] = new TreeGridNode(result.get(i).getServiceId(),
                    parentId,
                    result.get(i).getName(),
                    result.get(i).getDescription());
        }
        tree.setData(treeNodes);
        display.getTreeGrid().addDrawHandler(new DrawHandler() {
            public void onDraw(DrawEvent event) {
                tree.openAll();
            }
        });
        display.getTreeGrid().setSelectionAppearance(SelectionAppearance.CHECKBOX);
        display.getTreeGrid().setAnimateFolderEffect(AnimationAcceleration.SMOOTH_START_END);
        display.getTreeGrid().setData(tree);
        display.getTreeGrid().redraw();
        waiter.hide();
    }

    private void redrawEquipment(List<UIEquipment> result) {
        TreeGridField EquipmentIdField = new TreeGridField("Id");
        TreeGridField NameField = new TreeGridField("Name");
        TreeGridField DescriptionField = new TreeGridField("Description");
        display.getTreeGrid().setFields(EquipmentIdField, NameField, DescriptionField);
        final Tree tree = new Tree();
        tree.setModelType(TreeModelType.PARENT);
        tree.setNameProperty("Name");
        tree.setIdField("Id");
        tree.setParentIdField("ReportsTo");
        tree.setShowRoot(false);
        TreeNode[] treeNodes = new TreeNode[result.size()];
        for (int i = 0; i < treeNodes.length; ++i) {
            int parentId;
            if (result.get(i).getIsParent() == 1) {
                parentId = 0;
            } else {
                parentId = result.get(i).getParentId();
            }
            treeNodes[i] = new TreeGridNode(result.get(i).getEquipmentId(),
                    parentId,
                    result.get(i).getName(),
                    result.get(i).getDescription());
        }
        tree.setData(treeNodes);
        display.getTreeGrid().addDrawHandler(new DrawHandler() {
            public void onDraw(DrawEvent event) {
                tree.openAll();
            }
        });
        display.getTreeGrid().setSelectionAppearance(SelectionAppearance.CHECKBOX);
        display.getTreeGrid().setAnimateFolderEffect(AnimationAcceleration.SMOOTH_START_END);
        display.getTreeGrid().setData(tree);
        display.getTreeGrid().redraw();
    }

    private void doGoBack() {
        injector.getEventBus().fireEvent(new ManagerLoginEvent(this.currentStaff));
    }

    private void doAddNode() {
        createAddItemDialogBox();
    }

    private void createAddItemDialogBox() {
        final DialogBox waiter = Dialog.getInstance().createWaiter();
        final DialogBox dialogBox = new DialogBox();
        dialogBox.getElement().getStyle().setZIndex(500000);
        dialogBox.addStyleName("gwt-DialogBox");
        dialogBox.setText("Adding new " + type);
        final VerticalPanel dialogContents = new VerticalPanel();
        dialogContents.setStyleName("dialogContents");
        dialogBox.setWidget(dialogContents);
        dialogContents.setSpacing(4);
        final NewItemTreeGridViewPresenter newItemPresenter = new NewItemTreeGridViewPresenter(type);
        dialogContents.add(newItemPresenter.getDisplay().asWidget());
        newItemPresenter.getDisplay().getSaveButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                String itemName = newItemPresenter.getDisplay().getName().getText().replaceAll("\\s+", " ");
                if (itemName.length() <= 1) {
                    Dialog.getInstance().createDialogBoxWithMessage("Error", "Please provide valid item name");
                } else if (!newItemPresenter.getDisplay().getIsParent().getValue() && newItemPresenter.getDisplay().getCategory().getSelectedIndex() == 0) {
                    Dialog.getInstance().createDialogBoxWithMessage("Error", "Please choose the category or make item parent");
                } else {
                    if (type.equals("Equipment")) {
                        String selectedParentName = newItemPresenter.getDisplay().getCategory().getItemText(newItemPresenter.getDisplay().getCategory().getSelectedIndex());
                        int parentId = 0;

                        for (UIEquipment uiEquipment : newItemPresenter.getUiEquipmentList()) {
                            if (uiEquipment.getName().equals(selectedParentName)) {
                                parentId = uiEquipment.getEquipmentId();
                                break;
                            }
                        }
                        UIEquipment uiEquipment = new UIEquipment();
                        uiEquipment.setName(newItemPresenter.getDisplay().getName().getText());
                        uiEquipment.setDescription(newItemPresenter.getDisplay().getDescription().getText());
                        uiEquipment.setIsParent(newItemPresenter.getDisplay().getIsParent().getValue() ? 1 : 0);
                        uiEquipment.setParentId(parentId);

                        UserService.App.getInstance().addNewObjectToReferenceBook(uiEquipment, new AsyncCallback<Void>() {
                            @Override
                            public void onFailure(Throwable throwable) {
                                Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                            }

                            @Override
                            public void onSuccess(Void aVoid) {
                                UserService.App.getInstance().getEquipmentAllEquipment(new AsyncCallback<List<UIEquipment>>() {
                                    @Override
                                    public void onFailure(Throwable throwable) {
                                        Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                                    }

                                    @Override
                                    public void onSuccess(List<UIEquipment> result) {
                                        redrawEquipment(result);
                                        Dialog.getInstance().createDialogBoxWithMessage("New Item", "New equipment was successfully created");
                                        dialogBox.hide();
                                    }
                                });
                            }
                        });
                    } else if (type.equals("Service")) {
                        String selectedParentName = newItemPresenter.getDisplay().getCategory().getItemText(newItemPresenter.getDisplay().getCategory().getSelectedIndex());
                        int parentId = 0;

                        for (UIService uiService : newItemPresenter.getUiServiceList())
                            if (uiService.getName().equals(selectedParentName)) {
                                parentId = uiService.getServiceId();
                                break;
                            }

                        UIService uiService = new UIService();
                        uiService.setName(newItemPresenter.getDisplay().getName().getText());
                        uiService.setDescription(newItemPresenter.getDisplay().getDescription().getText());
                        uiService.setIsParent((newItemPresenter.getDisplay().getIsParent().getValue()) ? 1 : 0);
                        uiService.setParentId(parentId);

                        UserService.App.getInstance().addNewObjectToReferenceBook(uiService, new AsyncCallback<Void>() {
                            @Override
                            public void onFailure(Throwable throwable) {
                                Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                            }

                            @Override
                            public void onSuccess(Void aVoid) {
                                UserService.App.getInstance().getServiceAllService(new AsyncCallback<List<UIService>>() {
                                    @Override
                                    public void onFailure(Throwable throwable) {
                                        Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                                    }

                                    @Override
                                    public void onSuccess(List<UIService> result) {
                                        redrawService(result);
                                        Dialog.getInstance().createDialogBoxWithMessage("New Item", "New service was successfully created");
                                        dialogBox.hide();
                                    }
                                });
                            }
                        });
                    }
                }
//                else {
//                    String errorMessage = "Please choose category or make item parent";
//                    if (itemName.length() <= 1) {
//                        errorMessage = "Please provide valid item name";
//                    }
//                    Dialog.getInstance().createDialogBoxWithMessage("Error", errorMessage);
//                }
            }
        });
        newItemPresenter.getDisplay().getCancelButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                dialogBox.hide();
            }
        });
        dialogBox.setGlassEnabled(true);
        dialogBox.setAnimationEnabled(true);
        dialogBox.center();
        dialogBox.show();
        waiter.hide();
    }

    private void createEditItemDialogBox(Object object) {
        final DialogBox waiter = Dialog.getInstance().createWaiter();
        final DialogBox dialogBox = new DialogBox();
        dialogBox.getElement().getStyle().setZIndex(500000);
        dialogBox.addStyleName("gwt-DialogBox");
        dialogBox.setText("Edit " + type);
        final VerticalPanel dialogContents = new VerticalPanel();
        dialogContents.setStyleName("dialogContents");
        dialogBox.setWidget(dialogContents);
        dialogContents.setSpacing(4);
        final NewItemTreeGridViewPresenter newItemPresenter = new NewItemTreeGridViewPresenter(type, object);
        dialogContents.add(newItemPresenter.getDisplay().asWidget());
        newItemPresenter.getDisplay().getSaveButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                String itemName = newItemPresenter.getDisplay().getName().getText().replaceAll("\\s+", " ");
                if (itemName.length() <= 1) {
                    Dialog.getInstance().createDialogBoxWithMessage("Error", "Please provide valid item name");
                } else if (newItemPresenter.getDisplay().getIsParent().getValue()) {
                    Dialog.getInstance().createDialogBoxWithMessage("Error", "You are not able to change this item to parent");
                } else if (newItemPresenter.getDisplay().getCategory().getSelectedIndex() == 0) {
                    Dialog.getInstance().createDialogBoxWithMessage("Error", "Please, choose the category");
                } else {
                    if (type.equals("Equipment")) {
                        String selectedParentName = newItemPresenter.getDisplay().getCategory().getItemText(newItemPresenter.getDisplay().getCategory().getSelectedIndex());
                        int parentId = 0;

                        for (UIEquipment uiEquipment : newItemPresenter.getUiEquipmentList()) {
                            if (uiEquipment.getName().equals(selectedParentName)) {
                                parentId = uiEquipment.getEquipmentId();
                                break;
                            }
                        }
                        UIEquipment uiEquipment = (UIEquipment) newItemPresenter.getExistingItem();
                        uiEquipment.setName(newItemPresenter.getDisplay().getName().getText());
                        uiEquipment.setDescription(newItemPresenter.getDisplay().getDescription().getText());
                        uiEquipment.setIsParent(0);
                        uiEquipment.setParentId(parentId);

                        UserService.App.getInstance().updateEquipment(uiEquipment, new AsyncCallback<Void>() {
                            @Override
                            public void onFailure(Throwable throwable) {
                                Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                            }

                            @Override
                            public void onSuccess(Void aVoid) {
                                UserService.App.getInstance().getEquipmentAllEquipment(new AsyncCallback<List<UIEquipment>>() {
                                    @Override
                                    public void onFailure(Throwable throwable) {
                                        Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                                    }

                                    @Override
                                    public void onSuccess(List<UIEquipment> result) {
                                        redrawEquipment(result);
                                        Dialog.getInstance().createDialogBoxWithMessage("Edit Item", "Equipment was successfully edited");
                                        dialogBox.hide();
                                    }
                                });
                            }
                        });
                    } else if (type.equals("Service")) {
                        String selectedParentName = newItemPresenter.getDisplay().getCategory().getItemText(newItemPresenter.getDisplay().getCategory().getSelectedIndex());
                        int parentId = 0;

                        for (UIService uiService : newItemPresenter.getUiServiceList()) {
                            if (uiService.getName().equals(selectedParentName)) {
                                parentId = uiService.getServiceId();
                                break;
                            }
                        }
                        UIService uiService = (UIService) newItemPresenter.getExistingItem();
                        uiService.setName(newItemPresenter.getDisplay().getName().getText());
                        uiService.setDescription(newItemPresenter.getDisplay().getDescription().getText());
                        uiService.setIsParent(0);
                        uiService.setParentId(parentId);

                        UserService.App.getInstance().updateService(uiService, new AsyncCallback<Void>() {
                            @Override
                            public void onFailure(Throwable throwable) {
                                Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                            }

                            @Override
                            public void onSuccess(Void aVoid) {
                                UserService.App.getInstance().getServiceAllService(new AsyncCallback<List<UIService>>() {
                                    @Override
                                    public void onFailure(Throwable throwable) {
                                        Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                                    }

                                    @Override
                                    public void onSuccess(List<UIService> result) {
                                        redrawService(result);
                                        Dialog.getInstance().createDialogBoxWithMessage("Edit Item", "Service was successfully edited");
                                        dialogBox.hide();
                                    }
                                });
                            }
                        });
                    }
                }
            }
        });
        newItemPresenter.getDisplay().getCancelButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                dialogBox.hide();
            }
        });
        dialogBox.setGlassEnabled(true);
        dialogBox.setAnimationEnabled(true);
        dialogBox.center();
        dialogBox.show();
        waiter.hide();
    }

    private void doEditNode() {
        ListGridRecord[] records = display.getTreeGrid().getSelectedRecords();
        List<ListGridRecord> recordList = new ArrayList<ListGridRecord>();
        for (ListGridRecord record : records) {
            if (record.getAttribute("ReportsTo") != null) {
                recordList.add(record);
            }
        }
        if (recordList.size() != 1) {
            Dialog.getInstance().createDialogBoxWithMessage("Please,", "Select one item first.");
        } else {
            if (this.type.equals("Equipment")) {
                UIEquipment equipment = new UIEquipment();
                if (recordList.get(0).getAttribute("ReportsTo") == null) {
                    equipment.setParentId(0);
                    equipment.setIsParent(1);
                } else {
                    equipment.setParentId(recordList.get(0).getAttributeAsInt("ReportsTo"));
                    equipment.setIsParent(0);
                }
                equipment.setEquipmentId(recordList.get(0).getAttributeAsInt("Id"));
                equipment.setDescription(recordList.get(0).getAttribute("Description"));
                equipment.setName(recordList.get(0).getAttribute("Name"));
                createEditItemDialogBox(equipment);
            }
            if (this.type.equals("Service")) {
                UIService service = new UIService();
                if (recordList.get(0).getAttribute("ReportsTo") == null) {
                    service.setParentId(0);
                    service.setIsParent(1);
                } else {
                    service.setParentId(recordList.get(0).getAttributeAsInt("ReportsTo"));
                    service.setIsParent(0);
                }
                service.setServiceId(recordList.get(0).getAttributeAsInt("Id"));
                service.setDescription(recordList.get(0).getAttribute("Description"));
                service.setName(recordList.get(0).getAttribute("Name"));
                createEditItemDialogBox(service);
            }
        }
    }

    private void doDeleteNode() {
        if (this.type.equals("Equipment")) {
            final List<UIEquipment> equipmentsParentToDelete = new ArrayList<UIEquipment>();
            final List<UIEquipment> equipmentsChildToDelete = new ArrayList<UIEquipment>();
            ListGridRecord[] records = display.getTreeGrid().getSelectedRecords();
            for (ListGridRecord record : records) {
                UIEquipment equipment = new UIEquipment();
                if (record.getAttribute("ReportsTo") == null) {
                    equipment.setParentId(0);
                    equipment.setIsParent(1);
                } else {
                    equipment.setParentId(record.getAttributeAsInt("ReportsTo"));
                    equipment.setIsParent(0);
                }
                equipment.setEquipmentId(record.getAttributeAsInt("Id"));
                equipment.setDescription(record.getAttribute("Description"));
                equipment.setName(record.getAttribute("Name"));
                if (equipment.getIsParent() == 0) {
                    equipmentsChildToDelete.add(equipment);
                } else if (equipment.getIsParent() == 1) {
                    equipmentsParentToDelete.add(equipment);
                }
            }
            UserService.App.getInstance().deleteChildEquipmentList(equipmentsChildToDelete, new AsyncCallback<List<UIEquipment>>() {
                @Override
                public void onFailure(Throwable throwable) {
                    Dialog.getInstance().createDialogBoxWithMessage("Error", "Something went wrong, <br/>Anyway, here is the original message <br/> " + throwable.getMessage());
                }

                @Override
                public void onSuccess(List<UIEquipment> equipments) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (UIEquipment equipment : equipments) {
                        stringBuilder.append(equipment.getName()).append("\n");
                    }
                    if (!stringBuilder.toString().equals("")) {
                        Dialog.getInstance().createDialogBoxWithMessage("Error", "Could not be deleted equipments:\n" + stringBuilder.toString());
                    }
                    UserService.App.getInstance().deleteParentEquipmentList(equipmentsParentToDelete, new AsyncCallback<List<UIEquipment>>() {
                        @Override
                        public void onFailure(Throwable throwable) {
                            Dialog.getInstance().createDialogBoxWithMessage("Error", "Something went wrong, <br/>Anyway, here is the original message <br/> " + throwable.getMessage());
                        }

                        @Override
                        public void onSuccess(List<UIEquipment> equipments) {
                            StringBuilder stringBuilder = new StringBuilder();
                            for (UIEquipment equipment : equipments) {
                                stringBuilder.append(equipment.getName()).append("\n");
                            }
                            if (!stringBuilder.toString().equals("")) {
                                Dialog.getInstance().createDialogBoxWithMessage("Error", "Could not be deleted categories:\n" + stringBuilder.toString());
                            }
                            UserService.App.getInstance().getEquipmentAllEquipment(new AsyncCallback<List<UIEquipment>>() {
                                @Override
                                public void onFailure(Throwable throwable) {
                                    Dialog.getInstance().createDialogBoxWithMessage("Error", "Something went wrong, <br/>Anyway, here is the original message <br/> " + throwable.getMessage());
                                }

                                @Override
                                public void onSuccess(List<UIEquipment> result) {
                                    redrawEquipment(result);
                                }
                            });
                        }
                    });
                }
            });
        } else if (this.type.equals("Service")) {
            final List<UIService> servicesParentToDelete = new ArrayList<UIService>();
            final List<UIService> servicesChildToDelete = new ArrayList<UIService>();
            ListGridRecord[] records = display.getTreeGrid().getSelectedRecords();
            for (ListGridRecord record : records) {
                UIService service = new UIService();
                if (record.getAttribute("ReportsTo") == null) {
                    service.setParentId(0);
                    service.setIsParent(1);
                } else {
                    service.setParentId(record.getAttributeAsInt("ReportsTo"));
                    service.setIsParent(0);
                }
                service.setServiceId(record.getAttributeAsInt("Id"));
                service.setDescription(record.getAttribute("Description"));
                service.setName(record.getAttribute("Name"));
                if (service.getIsParent() == 0) {
                    servicesChildToDelete.add(service);
                } else if (service.getIsParent() == 1) {
                    servicesParentToDelete.add(service);
                }
            }
            UserService.App.getInstance().deleteChildServiceList(servicesChildToDelete, new AsyncCallback<List<UIService>>() {
                @Override
                public void onFailure(Throwable throwable) {
                    Dialog.getInstance().createDialogBoxWithMessage("Error", "Something went wrong, <br/>Anyway, here is the original message <br/> " + throwable.getMessage());
                }

                @Override
                public void onSuccess(List<UIService> services) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (UIService service : services) {
                        stringBuilder.append(service.getName()).append("\n");
                    }
                    if (!stringBuilder.toString().equals("")) {
                        Dialog.getInstance().createDialogBoxWithMessage("Error", "Could not be deleted services:\n" + stringBuilder.toString());
                    }
                    UserService.App.getInstance().deleteParentServiceList(servicesParentToDelete, new AsyncCallback<List<UIService>>() {
                        @Override
                        public void onFailure(Throwable throwable) {
                            Dialog.getInstance().createDialogBoxWithMessage("Error", "Something went wrong, <br/>Anyway, here is the original message <br/> " + throwable.getMessage());
                        }

                        @Override
                        public void onSuccess(List<UIService> services) {
                            StringBuilder stringBuilder = new StringBuilder();
                            for (UIService service : services) {
                                stringBuilder.append(service.getName()).append("\n");
                            }
                            if (!stringBuilder.toString().equals("")) {
                                Dialog.getInstance().createDialogBoxWithMessage("Error", "Could not be deleted categories:\n" + stringBuilder.toString());
                            }
                            UserService.App.getInstance().getServiceAllService(new AsyncCallback<List<UIService>>() {
                                @Override
                                public void onFailure(Throwable throwable) {
                                    Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                                }

                                @Override
                                public void onSuccess(List<UIService> result) {
                                    redrawService(result);
                                }
                            });
                        }
                    });
                }
            });
        }
    }

    @Override
    public void go(HasWidgets container) {
        container.clear();
        container.add(display.asWidget());
    }

    public interface Display {
        TreeGrid getTreeGrid();

        HasClickHandlers getAddNodeButton();

        HasClickHandlers getEditButton();

        HasClickHandlers getDeleteNodeButton();

        HasClickHandlers getBackButton();

        Widget asWidget();

        Label getRefsInfo();
    }
}
